import { CustomElement } from "@/js/components/CustomElement"

export class Drag {
    target: CustomElement
    container: CustomElement
    position = {
        left: 0,
        top: 0
    }

    down:any = null

    constructor(el:CustomElement,container: CustomElement){
        this.target = el
        this.container = container

        this.init()
    }

    init(){
        const move = ({movementX, movementY}:MouseEvent) => {
            this.position.left += movementX
            this.position.top += movementY

            this.target.setStyle({
                left: this.position.left + "px",
                top: this.position.top + "px",
            })

            this.onMove && this.onMove({...this.position, movementX, movementY})
        }

        const end = () => {
            this.container.removeEventListener("mousemove", move as EventListener)
            this.container.removeEventListener("mouseup", end)
        }

        const down = ()=>{
            this.position = {
                left: this.target.$el.offsetLeft,
                top: this.target.$el.offsetTop
            }
            this.container.addEventListener("mousemove", move as EventListener)
            this.container.addEventListener("mouseup", end)
        }

        this.down = down
        this.target.addEventListener("mousedown", this.down)
    }

    resetTarget(target: CustomElement){
        if(target) this.target.removeEventListener("mousedown", this.down)
        this.target = target
        this.init()
    }

    destory(){
        if(this.target) this.target.removeEventListener("mousedown", this.down)
    }

    onMove: any = null
}